﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using EKETEAM.FrameWork;
using EKETEAM.Data;
using EKETEAM.Tencent.WeChat;
using System.Web.Caching;
using System.Net;
using System.IO;
using System.Text;
using LitJson;


namespace eFrameWork.WeChat
{
    public partial class Login : System.Web.UI.Page
    {
        public string UserArea = "Application";
        eUser user;
        public string redirect_uri = "";

        private void ProxyLogin()
        {
            if (Request.QueryString["data"] != null)
            {
                #region 代理返回数据
                string data = Request.QueryString["data"].ToString();
                try
                {
                    string base64 = Base64.Decode(data);
                    if (base64.StartsWith("{"))
                    {
                        JsonData json = JsonMapper.ToObject(base64);
                        string openid = json.GetValue("openid");
                        string unionid = json.GetValue("unionid");
                        if (openid.Length == 0 && unionid.Length == 0)
                        {
                            Response.Write("授权失败!");
                            Response.End();
                        }
                        DataTable tb = eBase.UserInfoDB.getDataTable("select top 1 * from a_eke_sysUsers where (unionid='" + unionid + "' or openid='" + openid + "') and delTag=0 order by addTime");
                        if (tb.Rows.Count > 0)
                        {
                            #region 数据库存在该用户
                            if (tb.Rows[0]["Active"].ToString() == "False")
                            {
                                Response.Write("登录失败,用户信息已停用!");
                                Response.End();
                            }
                            if (tb.Rows[0]["delTag"].ToString() == "True")
                            {
                                Response.Write("登录失败,用户信息已删除!");
                                Response.End();
                            }
                            user = new eUser(UserArea);
                            eFHelper.saveUserInfo(user, tb.Rows[0]); //保存用户登录信息
                            eFHelper.UserLoginLog(user); //用户登录日志
                            string fromurl = eParameters.QueryString("fromURL");
                            if (fromurl.Length == 0)
                            {
                                Response.Redirect("Default.aspx", true);
                            }
                            else
                            {
                                Response.Redirect(HttpUtility.UrlDecode(fromurl), true);
                            }
                            #endregion
                        }

                    }
                    Response.End();
                }
                catch
                {
                }
                 #endregion
            }
            string self_url = HttpUtility.UrlEncode(Request.Url.AbsoluteUri);
            string url = eBase.WeChatAccount.getValue("Proxy") + "WeChat/loginProxy.aspx?fromURL=" + self_url;
            Response.Redirect(url, true);
            //eBase.Writeln(url);
            //eBase.End();

        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (eBase.WeChatAccount.getValue("Proxy").Length > 0)
            {
                ProxyLogin();
                return;
            }

            if (eBase.WeChatAccount.getValue("AppID").Length == 0 || eBase.WeChatAccount.getValue("AppSecret").Length == 0)
            {
                Response.Write("没有绑定域名、公众号或绑定信息不完整!");
                Response.End();
            }           
            string fromURL = eParameters.QueryString("fromURL");//登录来源页面URL
            user = new eUser(UserArea);
            if (user.Logined)
            {
                return;
            }
            eFileInfo fi = new eFileInfo(Request.Url.PathAndQuery);
            string folderPath = fi.Path;
            //redirect_uri = Request.Url.Scheme + "://" + Request.Url.Host;
            //redirect_uri += (Request.Url.Port == 80 || Request.Url.Port == 443 ? "" : ":" + Request.Url.Port.ToString()) + folderPath + "Login.aspx";

            redirect_uri = Request.Url.Scheme + "://" + eRequest.fromHost;
            redirect_uri += (eRequest.fromPort == 80 || eRequest.fromPort == 443 ? "" : ":" + eRequest.fromPort.ToString()) + folderPath + "Login.aspx";


            if (fromURL.Length > 0) redirect_uri += "?fromURL=" + HttpUtility.UrlEncode(HttpUtility.UrlEncode(fromURL)); // HttpUtility.UrlDecode(fromURL);
            redirect_uri = HttpUtility.UrlEncode(redirect_uri);


            string code = Request["code"];
            if (string.IsNullOrEmpty(code))
            {
                OpenAccess();
            }


            JsonData json = WeChatHelper.getAccessToken(code);

            string access_token = json.GetValue("access_token");
            string openid = json.GetValue("openid");
            string unionid = json.GetValue("unionid");
            if (openid.Length == 0 && unionid.Length==0)
            {
                Response.Write("授权失败!");
                Response.End();
            }
            DataTable tb = eBase.UserInfoDB.getDataTable("select top 1 * from a_eke_sysUsers where (openid='" + openid + "'" + (unionid.Length > 0 ? " or unionid='" + unionid + "'" : "") + ") and delTag=0 order by addTime");
            if (tb.Rows.Count > 0)
            {
                #region 数据库存在该用户
                if (tb.Rows[0]["Active"].ToString() == "False")
                {
                    Response.Write("登录失败,用户信息已停用!");
                    Response.End();
                }
                if (tb.Rows[0]["delTag"].ToString() == "True")
                {
                    Response.Write("登录失败,用户信息已删除!");
                    Response.End();
                }
                user = new eUser(UserArea);
                eFHelper.saveUserInfo(user, tb.Rows[0]); //保存用户登录信息
                eFHelper.UserLoginLog(user); //用户登录日志
                Response.Redirect(HttpUtility.UrlDecode(fromURL), true);
                #endregion
            }
            else
            {
                #region 添加用户
                JsonData _json = WeChatHelper.getUserInfo(access_token,openid);
                string headimgurl = _json.GetValue("headimgurl").Replace("\\", "");
                int mode = 1;//1.自动添加用户，2.让用户选择绑定现有帐号，或注册新帐号。
                if (mode == 2) //1.自动添加用户
                {
                    #region 自动添加用户
                    eTable etb = new eTable("a_eke_sysUsers");
                    etb.DataBase = eBase.UserInfoDB;
                    if (eBase.WeChatAccount.getValue("SiteID").Length > 0) etb.Fields.Add("SiteID", eBase.WeChatAccount.getValue("SiteID"));
                    etb.Fields.Add("UserType", "2");
                    etb.Fields.Add("RoleID", "201310aa-89d7-4209-b3c1-b507e1dc6267"); //默认具有角色的权限
                    // ,openid,nickname,sex,headimgurl,country,province,city,unionid
                    etb.Fields.Add("openid", openid);
                    etb.Fields.Add("nickname", _json.GetValue("nickname"));
                    etb.Fields.Add("sex", _json.GetValue("sex"));                
                    etb.Fields.Add("headimgurl", headimgurl);
                    etb.Fields.Add("country", _json.GetValue("country"));
                    etb.Fields.Add("province", _json.GetValue("province"));
                    etb.Fields.Add("city", _json.GetValue("city"));
                    if( _json.GetValue("unionid").Length > 0)  etb.Fields.Add("unionid", _json.GetValue("unionid"));                   
                    etb.Add();
             
                    string userid = etb.ID;
                    string face = WeChatHelper.downHeadImage(userid, headimgurl);
                    tb = eBase.UserInfoDB.getDataTable("select top 1 * from a_eke_sysUsers where UserID='" + userid + "'");
                    if (tb.Rows.Count > 0)
                    {
                        user = new eUser(UserArea);
                        eFHelper.saveUserInfo(user, tb.Rows[0]); //保存用户登录信息
                    }
                    eFHelper.UserLoginLog(user); //用户登录日志
                    Response.Redirect(HttpUtility.UrlDecode(fromURL), true);
                    #endregion
                }
                else //让用户选择绑定现有帐号，或注册新帐号。
                {


                    JsonData jd = new JsonData();
                    jd["openid"] = openid;
                    jd["nickname"] = _json.GetValue("nickname");
                    jd["sex"] = _json.GetValue("sex");
                    jd["headimgurl"] = headimgurl;
                    jd["country"] = _json.GetValue("country");
                    jd["province"] = _json.GetValue("province");
                    jd["city"] = _json.GetValue("city");
                    if (_json.GetValue("unionid").Length > 0) jd["unionid"] = _json.GetValue("unionid"); 

                    jd["fromURL"] = fromURL;
                    Session["WeChat_UserInfo"] = jd.ToJson();
                    Response.Redirect("BindChoose.aspx", true);
                }
                #endregion
            }
        }
        private void OpenAccess()
        {
            if (!user.Logined)
            {
                string url = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_userinfo&m=oauth2#wechat_redirect", eBase.WeChatAccount.getValue("AppID"), redirect_uri);
                Response.Redirect(url);
            }
            else
            {
                Response.Redirect(Request.Url.ToString());
            }

        }
    
    }
}